from flask import Blueprint, request, current_app, jsonify
from werkzeug.utils import secure_filename
import json
import os
import logging
from utils import allowed_file, unique_filename
from modules.template_match.service import process_template_matching

# 创建蓝图
template_match_blueprint = Blueprint('template_match', __name__)
logger = logging.getLogger("template_match")


@template_match_blueprint.route("/template-match", methods=["POST"])
def template_match_route():
    """
    模板匹配API端点

    需要上传两个文件:
    - target_image: 要搜索的目标图像
    - template_image: 要匹配的模板图像

    可选参数 (作为JSON字符串通过form-data中的'data'字段提供):
    - method: 匹配方法 ('feature', 'template', 'hybrid')
    - params: 根据方法的额外参数

    返回:
    - 200 OK: 匹配结果
    - 400 Bad Request: 请求错误
    - 500 Internal Server Error: 服务器处理错误
    """
    # 检查是否有文件上传
    if "target_image" not in request.files or "template_image" not in request.files:
        return {"error": "缺少必要的图像文件"}, 400

    target_file = request.files["target_image"]
    template_file = request.files["template_image"]

    # 验证文件名
    if target_file.filename == "" or template_file.filename == "":
        return {"error": "未选择文件"}, 400

    # 验证文件类型
    if not (allowed_file(target_file.filename, current_app.config["ALLOWED_EXTENSIONS"]) and
            allowed_file(template_file.filename, current_app.config["ALLOWED_EXTENSIONS"])):
        return {"error": "不支持的文件类型"}, 400

    try:
        # 解析请求参数
        data = {}
        if 'data' in request.form:
            try:
                data = json.loads(request.form.get("data"))
            except Exception as e:
                logger.warning(f"解析请求数据出错: {str(e)}")

        method = data.get("method", "hybrid")
        params = data.get("params", {})

        # 处理匹配请求
        result, status_code = process_template_matching(
            target_file,
            template_file,
            method,
            params
        )

        return jsonify(result), status_code

    except Exception as e:
        logger.exception(f"模板匹配处理出错: {str(e)}")
        return {"error": f"处理过程中出错: {str(e)}"}, 500

    finally:
        pass
